package com.wyl.circularDependency;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 吴宇亮 on 2022/3/17 10:54
 */
@Component
public class CircularDependInit implements ApplicationContextAware, InitializingBean {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        BeanA beanA = applicationContext.getBean(BeanA.class);
        BeanB beanB  = applicationContext.getBean(BeanB.class);

        Field beanASetBeanB = BeanA.class.getDeclaredField("beanB");
        beanASetBeanB.setAccessible(true);
        beanASetBeanB.set(beanA, beanB);

        Field beanBSetBeanA = BeanB.class.getDeclaredField("beanA");
        beanBSetBeanA.setAccessible(true);
        beanBSetBeanA.set(beanB, beanA);
    }
}
